<template>
  <div class="center-container">
    <action-field v-model:global-state="globalState" />
    <div
      :class="[
        'Canvas',
        { phoneCav: agentType === 'phone', tabletCav: agentType === 'tablet' },
      ]"
    >
      <!-- 弹性盒子渲染 -->
      <component
        v-for="(item, index) in centerView"
        v-model:com-data="centerView[index]"
        :is="item.comName"
        :key="item.id"
        :isEdit="globalState.isEdit"
        :style="item.style"
        @click.stop="onPointed(item)"
        @dragenter.stop="onDragEnter($event, item)"
      />
      <div class="addBtn" @click="addFlexBox(centerView)">
        <PlusCircleFilled style="color: #2f77ff; font-size: 20px" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, reactive } from "vue";
import actionField from "./actionField";
import useGetState from "@/utils/useGetState";
import { useStore } from "vuex";
import { createNewCom, isObjEqual } from "@/utils/index";

import { PlusCircleFilled } from "@ant-design/icons-vue";
const store = useStore();
const { agentType } = useGetState(store, ["agentType"]);

const globalState = reactive({
  isEdit: true,
  step: -1,
  beginIndex: 0,
  isRoll: false,
});

const centerView = computed({
  set: (val) => {
    store.commit("setCenterView", val);
  },
  get: () => store.state.centerView,
});
//点击画布主按钮
const addFlexBox = (arr) => {
  const flexBox = createNewCom("FlexBox");
  arr.push(...flexBox);
};
const onPointed = (comData) => {
  store.dispatch("setSelectedCom", { comData });
};
const onDragEnter = (e, comData) => {
  e.preventDefault();
  onPointed(comData);
};
const newList = computed(() => JSON.parse(JSON.stringify(centerView.value)));

watch(
  newList,
  (newVal, oldVal) => {
    //判断是否需要缓存
    if (!oldVal || !newVal) {
      globalState.step++;
      return sessionStorage.setItem(
        String(globalState.step),
        JSON.stringify([])
      );
    }
    if (globalState.isRoll) {
      return (globalState.isRoll = false);
    }
    if (!isObjEqual(oldVal, newVal)) {
      globalState.step++;
      sessionStorage.setItem(String(globalState.step), JSON.stringify(newVal));
      if (sessionStorage.getItem(String(globalState.step + 1))) {
        sessionStorage.removeItem(String(globalState.step + 1));
      }
      //只保存30次的操作
      if (globalState.step >= globalState.beginIndex + 30) {
        sessionStorage.removeItem(String(globalState.beginIndex++));
      }
    }
  },
  { deep: true, immediate: true }
);
// export default {
//   name: 'CenterCom',
//   mounted() {
//     //注册$bus挂载的事件
//     eventHandler(['isNew', 'Pointed', 'addChildFlexBox', 'dropCom', 'dragStartEvent', 'dragEnter', 'backOff',
//       'forward', 'importJSON', 'reset', 'save', 'deleteCom', 'changeCanva', 'saveJSON', 'outputJson'], this)
//   },
//   data() {
//     return {
//       dataList: [],
//       isNew: false, //拖动的是否为新组件
//       edit: true,
//       currentCom: {},
//       currentView: [],
//       currentIndex: -1,
//       preCom: {},
//       preFatherCom: {},
//       preIndex:-1,
//       isPC: true,
//       step: 1,
//       begin: 1,
//       isRoll: false,
//     }
//   },
//   methods: {
//     //父flexbox点击的pointer
//     pointed (node, index) {
//       if (this.currentIndex !== index) {
//         this.dataTransfer(this.dataList,node,index)
//         this.focus(node)
//       }
//     },
//     //组件的聚焦
//     focus(node) {
//       this.clearFocus()
//       node.focus = true
//       this.$bus.emit('sendViews', this.currentCom)
//     },
//     drop(e, view) {
//       e.preventDefault()
//       // let offY = e.dataTransfer.getData('comOffsetY') //获取鼠标相对组件位置
//       // let offX = e.dataTransfer.getData('comOffsetX')
//       // let left = e.offsetX - offX > 0 ? e.offsetX - offX : 0
//       // let right = e.offsetY - offY > 0 ? e.offsetY - offY : 0
//       if (this.isNew) {
//         let name = e.dataTransfer.getData('comName')
//         const newData = deepCopy(commonData[name])
//         newData.id = nanoid(5)
//         newData.comName = name
//         // newData.style.left = left + 'px'
//         // newData.style.top = right + 'px'
//         view.children.push(newData)
//         this.isNew = false
//         // this.$refs.canvas.style.backgroundColor = '#d1d1d1'
//       } else {
//         // this.dataList[this.comIndex].style.left = left + 'px'
//         // this.dataList[this.comIndex].style.top = right + 'px'
//         view.children.push(this.currentCom)
//         this.deleteCom(this.preFatherCom,this.preIndex)
//         // this.$refs.canvas.style.backgroundColor = '#d1d1d1'
//       }
//     },
//     clearFocus () {
//       this.preCom.focus = false
//     },
//     dataTransfer(view, node, index) {
//       this.preCom = this.currentCom
//       this.preFatherCom = this.currentView
//       this.preIndex = this.currentIndex
//       this.currentView = view
//       this.currentCom = node
//       this.currentIndex = index
//     },
//     addFlexBox(arr) {
//       const FlexBox = deepCopy(commonData['FlexBox'])
//       FlexBox.id = nanoid(5)
//       arr.push(FlexBox)
//     },
//     addChildFlexBox(view) {
//       if (view.children.length == 0) this.addFlexBox(view.children)
//       this.addFlexBox(view.children)
//     },
//     isEqual(objA, objB) {
//       //获得两个对象的属性数组
//       objA = objA || {}
//       objB = objB || {}
//       const aPorps = Object.getOwnPropertyNames(objA)
//       const bPorps = Object.getOwnPropertyNames(objB)
//       if (aPorps.length != bPorps.length) {
//         return false
//       }
//       for (let i = 0; i < aPorps.length; i++) {
//         const propName = aPorps[i]
//         const type = typeof objA[propName]
//         if (type == 'object') {
//           if (!this.isEqual(objA[propName], objB[propName])) return false
//         } else if (objA[propName] !== objB[propName]) {
//           if (propName != 'focus') return false
//           //如果是属性focus不一样就继续比较
//         }
//       }
//       return true
//     },
//     deleteCom (fatherCom, index) {
//       fatherCom.splice(index,1)
//     }
//   },
//   computed: {
//     newList() {
//       return JSON.parse(JSON.stringify(this.dataList))
//     },
//   },
//   watch: {
//     newList: {
//       deep: true,
//       immediate: true,
//       handler(newVal, oldVal) {
//         //判断两个对象是否一致
//         if (!oldVal || !newVal) {
//           sessionStorage.setItem(String(this.step), JSON.stringify([]))
//           return
//         }
//         if (this.isRoll) {
//           this.isRoll = false
//           return
//         }
//         if (!this.isEqual(newVal, oldVal)) {
//           this.step++
//           sessionStorage.setItem(String(this.step), JSON.stringify(newVal))
//           if (sessionStorage.getItem(String(this.step + 1)) !== null) {
//             sessionStorage.removeItem(String(this.step + 1))
//           }
//           // 如果数据大于100就删前50个
//           if (this.step - this.begin > 100) {
//             for (let i = this.begin; i < this.begin + 50; i++) {
//               sessionStorage.removeItem(String(i))
//             }
//             this.begin += 50
//           }
//         }
//       },
//     },
//   },

//   components: {
//     Top,
//   },
// }
</script>

<style lang="less" scoped>
.center-container {
  position: relative;
  width: 100%;
  height: 100%;
  -o-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
  overflow-y: auto;
  .Canvas {
    position: relative;
    display: flex;
    min-height: calc(100% - 54px);
    flex-direction: column;
    background-color: #fff;
    border: 1px dashed #409eff;
    margin: 10px 10px 0 10px;
    .addBtn {
      margin-top: 6px;
      cursor: pointer;
    }
  }

  .phoneCav {
    width: 375px;
    min-height: 667px;
    overflow-y: auto;
    margin: 10px auto;
  }
  .tabletCav {
    width: 450px;
    min-height: 667px;
    overflow-y: auto;
    margin: 10px auto;
  }
}
</style>
